//
//  PopoverAnimation.swift
//  sina_yl
//
//  Created by 袁量 on 2017/5/22.
//  Copyright © 2017年 袁量. All rights reserved.
//

import UIKit

class PopoverAnimation: NSObject {
    lazy var presentViewFrame : CGRect = CGRect.zero
    /// 表示是弹出还是消失
    var isPresent : Bool = false
    var callBack : ((_ presented : Bool) -> ())?
    init(callBack : @escaping (_ presented : Bool) -> ()) {
        self.callBack = callBack
    }
}
extension PopoverAnimation : UIViewControllerTransitioningDelegate {
    func presentationController(forPresented presented: UIViewController, presenting: UIViewController?, source: UIViewController) -> UIPresentationController? {
        let presention = YLPresentationController(presentedViewController: presented, presenting: presenting)
        presention.presentViewFrame = presentViewFrame
        return presention
    }
    func animationController(forPresented presented: UIViewController, presenting: UIViewController, source: UIViewController) -> UIViewControllerAnimatedTransitioning? {
        isPresent = true
        callBack!(isPresent)
        return self
    }
    func animationController(forDismissed dismissed: UIViewController) -> UIViewControllerAnimatedTransitioning? {
        isPresent = false
        callBack!(isPresent)
        return self
    }
}
extension PopoverAnimation : UIViewControllerAnimatedTransitioning {
    func transitionDuration(using transitionContext: UIViewControllerContextTransitioning?) -> TimeInterval {
        return 0.5
    }
    func animateTransition(using transitionContext: UIViewControllerContextTransitioning) {
        isPresent ? animationForPresentingView(using: transitionContext) : animationForDismissedView(using: transitionContext)
    }
    func animationForPresentingView(using transitionContext: UIViewControllerContextTransitioning) {
        let presentedView = transitionContext.view(forKey: .to)!
        transitionContext.containerView.addSubview(presentedView)
        presentedView.transform = CGAffineTransform(scaleX: 1.0, y: 0.0)
        presentedView.layer.anchorPoint = CGPoint(x: 0.5, y: 0)
        UIView.animate(withDuration: transitionDuration(using: transitionContext), animations: {
            presentedView.transform = CGAffineTransform.identity
            
        }) { (_) in
            transitionContext.completeTransition(true)
        }
        
    }
    func animationForDismissedView(using transitionContext: UIViewControllerContextTransitioning) {
        let dismissView = transitionContext.view(forKey: .from)!
        UIView.animate(withDuration: transitionDuration(using: transitionContext), animations: {
            dismissView.transform = CGAffineTransform(scaleX: 1.0, y: 0.01)
        }) { (_) in
            dismissView.removeFromSuperview()
            transitionContext.completeTransition(true)
        }
    }
}

